import InsUtils from "./ins-utils";
import {BOOLEAN, INS_KEY} from "../configs/config";
import Redis from "ioredis";

const insUtils = new InsUtils();

/**
 * Redis工具
 */
class RedisUtils {

    /**
     * 将数据存入缓存
     * @param key
     * @param value
     * @param expireSeconds 过期时间(秒)
     */
    setStr = async (key: string, value: string, expireSeconds: number = -1) => {
        const log = global.logUtils.createContext('RedisUtils', 'setStr');

        const redisClient: Redis = insUtils.getIns(INS_KEY.REDIS_KEY);
        log.debug(`将数据存入Redis，key: ${key}，过期时间：${expireSeconds}秒，内容为：${value}`);
        return new Promise(((resolve, reject) => {
            redisClient.set(key, value, (resp) => {
                // 没有错误信息返回，证明存入成功
                if(!resp) {
                    log.debug(`key: ${key} 存入成功`);
                    (expireSeconds !== -1 ) && redisClient.expire(key, expireSeconds);
                    resolve(BOOLEAN.YES);
                } else {
                    log.debug(`key: ${key} 存入失败，原因：`, resp);
                    reject(resp);
                }
            });
        }))
    }

    /**
     * 获取缓存中的数据
     * @param key
     */
    getStr = async (key: string): Promise<string | null> => {
        const log = global.logUtils.createContext('RedisUtils', 'getStr');

        const redisClient: Redis = insUtils.getIns(INS_KEY.REDIS_KEY);
        const value = await redisClient.get(key);
        // log.debug(`获取key：${key} 对应的数据为：${value}`);
        return value;
    }

    /**
     * 删除redis缓存
     * @param key
     */
    delete = (key: string) => {
        const log = global.logUtils.createContext('RedisUtils', 'delete');

        const redisClient: Redis = insUtils.getIns(INS_KEY.REDIS_KEY);
        redisClient.del(key);
        log.debug(`删除缓存key：${key}`);
    }
}

export default RedisUtils;